package com.stlm2.core.oauth;

import com.stlm2.util.HttpSend;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author：fuchunyu
 * Date：2017/11/11
 * Description：
 */
public class AdvancedUtil {
    /**
     * 获取网页授权凭证
     *
     * @param appId 公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static WeixinOauth2Token getWxAccessToken(String appId, String appSecret, String code) {
        WeixinOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                wat = new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInt("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.println("获取网页授权凭证失败 errcode："+errorCode+" errmsg："+errorMsg);
            }
        }
        return wat;
    }

    /**
     * 获取网页授权凭证
     *
     * @param client_id 公众账号的唯一标识
     * @param client_secret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static QqOauth2Token getQqAccessToken(String client_id, String client_secret, String code) {
        QqOauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://graph.qq.com/oauth2.0/token";
        String param="grant_type=authorization_code&client_id=101442252&client_secret=2b3d1944b44d5193cf2b827b03c64bc6&code="+code+"&redirect_uri=http%3a%2f%2fddt.chinaddcat.com%2fm%2fphoneHtml%2fbaiye.html";
        // 获取网页授权凭证
        String getAddress = HttpSend.getSend(requestUrl, param);
        String splits[]=getAddress.split("&");
        Map<String,String> map=new HashMap<String, String>();
        for (String s:splits){
            String split[]=s.split("=");
            map.put(split[0],split[1]);
        }
        JSONObject jsonObject=JSONObject.fromObject(map);
        if (null != jsonObject) {
            try {
                wat = new QqOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInt("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                 String requestUrl2="https://graph.qq.com/oauth2.0/me";
                 String param2="access_token="+wat.getAccessToken();
                String getAddress1 = HttpSend.getSend(requestUrl2, param2);
                getAddress1=getAddress1.replace("callback(","").replace(");","").trim();
                /*jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);*/
                JSONObject jsonObject1=JSONObject.fromObject(getAddress1);
                if (null != jsonObject1) {
                    wat.setOpenId(jsonObject1.getString("openid"));
                }
            } catch (Exception e) {
                wat = null;
                int error = jsonObject.getInt("error");
                String error_description = jsonObject.getString("error_description");
                System.out.println("获取网页授权凭证失败 error："+error+" error_description："+error_description);
            }
        }
        return wat;
    }
    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings( { "deprecation", "unchecked" })
    public static WxUserInfo getWxUserInfo(String accessToken, String openId) {
        WxUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        System.out.println("jsonObject：---"+jsonObject.toString());

        if (null != jsonObject) {
            try {
                snsUserInfo = new WxUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                snsUserInfo.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));
                //用户全平台唯一标识
                snsUserInfo.setUnionid(jsonObject.getString("unionid"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.println("获取用户信息失败 errcode："+errorCode+" errmsg："+errorMsg);
            }
        }
        return snsUserInfo;
    }

    public static QqUserInfo getQqUserInfo(String accessToken,String oauth_consumer_key, String openId) {
        QqUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://graph.qq.com/user/get_user_info";
        String param="access_token=ACCESS_TOKEN&oauth_consumer_key=OAUTH_CONSUMER_KEY&openid=OPENID";
        param = param.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId).replace("OAUTH_CONSUMER_KEY",oauth_consumer_key);
        // 通过网页授权获取用户信息
        String getAddress=HttpSend.getSend(requestUrl,param);
        /*JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);*/
        JSONObject jsonObject=JSONObject.fromObject(getAddress);
        System.out.println("jsonObject：---"+jsonObject.toString());

        if (null != jsonObject) {
            try {
                snsUserInfo = new QqUserInfo();
                // 用户的标识
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 昵称
                snsUserInfo.setFigureurl_qq_2(jsonObject.getString("figureurl_qq_2"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInt("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                System.out.println("获取用户信息失败 errcode："+errorCode+" errmsg："+errorMsg);
            }
        }
        return snsUserInfo;
    }

}
